package com.xb.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xb.entity.Dict;
import com.xb.entity.Drug;
import com.xb.entity.Stock;
import com.xb.mapper.DictMapper;
import com.xb.mapper.DrugMapper;
import com.xb.mapper.StockMapper;
import com.xb.service.IDrugService;
import com.xb.util.Result;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service业务层处理
 */
@Service
public class DrugServiceImp implements IDrugService {
    @Resource
    private DrugMapper drugMapper;
    @Resource
    private DictMapper dictMapper;
    @Resource
    private StockMapper stockMapper;


    @Transactional
    @Override
    public Result updateDrugAndDict(Drug drug) {
        Result result = new Result();
        try {
            String oldName = drugMapper.selectDrugById(drug.getId()).getName();
            if (drugMapper.updateDrug(drug) == 0) {
                throw new RuntimeException("drug修改失败");
            }
            Map<String, String> map = new HashMap<>();
            map.put("oldName", oldName);
            map.put("newName", drug.getName());
            map.put("typeNo", "drug_name");
            if (dictMapper.updateDictByDictOldName(map) == 0) {
                throw new RuntimeException("dict修改失败");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (RuntimeException e) {
            result.setMessage(e.getMessage() + "请联系管理员");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        } catch (Exception e) {
            result.setMessage("出现异常请联系管理员");
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }

    }

    @Override
    public Drug getDrugInfo(String name) {
        return drugMapper.selectDrugByName(name);
    }

    @Transactional
    @Override
    public Result deleteDrugAndDict(String name, Integer id) {
        Result result = new Result();
        try {
            if (name == null || id == null) {
                throw new IllegalAccessException("删除内容为空！");
            }
            if (drugMapper.deleteDrugById(id) == 0) {
                throw new IllegalAccessException("drug删除失败！");
            }
            if (dictMapper.deleteDictByName(name) == 0) {
                throw new IllegalAccessException("dict删除失败！");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (Exception e) {
            result.setMessage(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
    }

    @Transactional
    @Override
    public Result addStorageQuantity(Drug drug) {
        Result result = new Result();
        try {
            Drug oldDrugInfo = drugMapper.selectDrugByName(drug.getName());
            if (oldDrugInfo == null) {
                throw new RuntimeException("未找到该药品信息！请核实药品库是否有该药品！");
            }
            Stock stock = new Stock();
            stock.setDrugId(oldDrugInfo.getId());
            stock.setNum(drug.getDrugCount());
            stock.setPrice(oldDrugInfo.getWholesalePrice());
            stock.setMoney(stock.getNum() * stock.getPrice());
            stock.setSupplier(oldDrugInfo.getManufacturer());
            if (stockMapper.insertStock(stock) == 0) {
                throw new RuntimeException("stock添加失败");
            }
            drug.setDrugCount(drug.getDrugCount() + oldDrugInfo.getDrugCount());
            if (drugMapper.addStorageQuantity(drug) == 0) {
                throw new RuntimeException("入库失败");
            }
            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;
        } catch (RuntimeException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMessage(e.getMessage() + "请联系管理员");
            return result;
        }

    }

    @Transactional
    @Override
    public Result addNewDrug(Drug drug) {
        Result result = new Result();
        try {
            if (drugMapper.selectDrugByName(drug.getName()) != null) {
                throw new IllegalAccessException("已有该药品名称！");
            }
//            List<String> list = dictMapper.selectDictByTypeNo("drug_name");
//            if (list.stream().anyMatch(s -> s.equals(drug.getName()))) {
//                throw new IllegalAccessException("词典已有该药品名称！");
//            }
            if (drugMapper.insertDrug(drug) == 0) {
                throw new IllegalAccessException("药品添加失败！");
            }
            Stock stock = new Stock();
            stock.setDrugId(drug.getId());
            stock.setNum(drug.getDrugCount());
            stock.setPrice(drug.getWholesalePrice());
            stock.setMoney(stock.getNum() * stock.getPrice());
            stock.setSupplier(drug.getManufacturer());
            if (stockMapper.insertStock(stock) == 0) {
                throw new RuntimeException("stock添加失败");
            }
            boolean drugNameBo = false;
            List<String> drugName = dictMapper.selectDictByTypeNo("drug_name");
            for (String s : drugName) {
                if (s.equals(drug.getName())) {
                    drugNameBo = true;
                    break;
                }
            }
            if (!drugNameBo) {
                Dict dict = new Dict();
                dict.setTypeNo("drug_name");
                dict.setHierarchy(5);
                dict.setName(drug.getName());
                dict.setRemark("药物名称");
                if (dictMapper.insertDict(dict) == 0) {
                    throw new IllegalAccessException("词典添加失败！");
                }
            }
            boolean manufacturerBo = false;
            List<String> manufacturer = dictMapper.selectDictByTypeNo("manufacturer");
            for (String s : manufacturer) {
                if (s.equals(drug.getManufacturer())) {
                    manufacturerBo = true;
                    break;
                }
            }
            if (!manufacturerBo) {
                Dict dict2 = new Dict();
                dict2.setTypeNo("manufacturer");
                dict2.setHierarchy(5);
                dict2.setName(drug.getManufacturer());
                dict2.setRemark("生产厂家");
                if (dictMapper.insertDict(dict2) == 0) {
                    throw new IllegalAccessException("词典添加失败！");
                }
            }

            result.setStatus(Result.RESPONSE_SUCCESS);
            return result;


        } catch (IllegalAccessException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            result.setMessage(e.getMessage());
            return result;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            result.setMessage("出错了！请联系管理员");
            return result;
        }
    }

    @Override
    public Result addDrugType(Dict dict) {
        Result result = new Result();
        List<Dict> dictList = dictMapper.selectAllDictByTypeNo(dict.getTypeNo());
        for (Dict dict1 : dictList) {
            if (dict1.getName().equals(dict.getName())) {
                result.setMessage(dict.getName() + "已存在！");
                return result;
            }
        }
        if (dictMapper.insertDict(dict) > 0) {
            result.setStatus(Result.RESPONSE_SUCCESS);
        }
        return result;
    }

    /**
     * 分页查询列表
     *
     * @param drug
     * @return
     */
    @Override
    public PageInfo<Drug> selectDrugList(Drug drug, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Drug> list = drugMapper.selectDrugList(drug);
        return new PageInfo<Drug>(list);
    }


    @Override
    public List<Drug> selectAllDrugList() {
        return drugMapper.selectAllDrugList();
    }


    /**
     * 修改
     *
     * @param drug
     * @return 结果
     */
    @Override
    public int updateDrug(Drug drug) {
        return drugMapper.updateDrug(drug);
    }

    /**
     * 删除信息
     *
     * @param id ID
     * @return 结果
     */
    @Override
    public int deleteDrugById(Integer id) {
        return drugMapper.deleteDrugById(id);
    }
}
